﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using Akiha.Core;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.DataSourcesGDB;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.esriSystem;
using DevExpress.XtraTreeList.Columns;
using DevExpress.XtraTreeList.Nodes;


namespace ArcMap_AddIn_Tools.FeatureClass.TinyPloygonCheck
{
    public partial class FormTinyPloygonCheck : Form
    {
        public FormTinyPloygonCheck()
        {
            InitializeComponent();
        }







        private IMap m_Map=null;

        private double m_dblTolerance;

        private IFeatureLayer m_CurrentLayer = null;

        //当前dgv中显示的table
        private DataTable m_dt = null;

        private void FormTinyPloygonCheck_Load(object sender, EventArgs e)
        {
            m_Map = ArcMap.Document.FocusMap;


            LoadLayerToTreeList(m_Map);

            
        }



        //通过FeaLyr初始化新的dt
        private void initDataTable(ILayer pFeaLyr)
        {
            //表名为图层名
            if (m_dt!=null)
            {
                m_dt.Dispose();
            }

            m_dt = new DataTable(pFeaLyr.Name);
            ITable pTable = (ITable)pFeaLyr;
            try
            {
                for (int i = 0; i < pTable.Fields.FieldCount; i++)
                {
                    DataColumn pDataColumn = new DataColumn();
                    
                    pDataColumn.Caption = pTable.Fields.get_Field(i).Name;
                   
                    pDataColumn.ColumnName = pTable.Fields.get_Field(i).AliasName;
                    // pDataColumn.ColumnName = pTable.Fields.get_Field(i).Name.ToString();
                   
                   
                    m_dt.Columns.Add(pDataColumn);
                }
            }
            catch (Exception ex)
            {
                return ;
            }
           

        }





        //检查微小面
        private List<IFeature> CheckTinyPloygon(double tolerence, List<IFeature> lstInFeatures)
        {
            List<IFeature> lstFea=new List <IFeature>();    
            foreach (IFeature pFea in lstInFeatures)
            {
                //查找实体的面积
               IGeometry pGeo=pFea.Shape;
               IArea pArea=(IArea)pGeo;
               double dblArea=pArea.Area; 
                if (dblArea<=tolerence)
                {
                    lstFea.Add(pFea);
                }
            }
            return lstFea;
        }


        //载入符合要求的面图层到list中
        private void LoadLayerToTreeList(IMap pMap)
        {

           //初始化treelist的列
            //object列不显示
            string[] strCol={"引用","图层名称"};
            for (int i = 0; i < 2; i++)
			{
                TreeListColumn treeCol =treeList1.Columns.Add();
                treeCol.Caption=strCol[i];
                treeCol.VisibleIndex=0==i?-1:i-1;	 
			}

            
	    


           List<IFeatureLayer> lstFeaLyr= MapWrapper.GetLayers(pMap, null);
           treeList1.BeginUnboundLoad();
           foreach (IFeatureLayer pFeaLyr in lstFeaLyr)
           {
               if (pFeaLyr.FeatureClass==null)
               {
                   continue;
               }
               //载入符合要求的面图层到根图层
               if (pFeaLyr.FeatureClass.ShapeType== esriGeometryType.esriGeometryPolygon)
               {
                  TreeListNode node= treeList1.AppendNode(new object[] { pFeaLyr, pFeaLyr.FeatureClass.AliasName }, null);
                  node.HasChildren = false;                    
               }
           }
           treeList1.EndUnboundLoad();

        }








        
        //载入查找到的要素到grid中
        private void LoadFeaturesToGrid(List<IFeature> lstFea,DataTable dt)
        {
            if (lstFea.Count==0)
	        {
                return ;
	        }
            if (dt==null)
            {
                return;
            }
            foreach (IFeature pFea in lstFea)
            {               
                DataRow pDataRow = dt.NewRow();
                IRow pRow = pFea;
                string str = "";
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (pRow.Fields.get_Field(j).Name == "SHAPE")
                    {
                        str = pFea.Shape.GeometryType.ToString();
                    }
                    else
                    {
                        str = pRow.get_Value(j).ToString();
                    }    
                    pDataRow[j] = str;
                }
                dt.Rows.Add(pDataRow);
            }
            //dgvFeatures.Columns.text
            dgvFeatures.DataSource = dt.DefaultView; 
        }


        //检查容限值
        private bool CheckTolerance()
        {
            string strTolerance = txtTolerance.Text;
            try
            {
                double dblTolerance = Convert.ToDouble(strTolerance);

                if (dblTolerance <= 0)
                {
                    MessageBox.Show("请输入符合条件的容限值", "提示");
                    return false;
                }
                m_dblTolerance = dblTolerance;
                return true;

            }
            catch (Exception ex)
            {
                MessageBox.Show("请输入符合条件的容限值", "提示");
                return false;
            }
            
        }


        private void btnCheck_Click(object sender, EventArgs e)
        {
            //获取当前的node

            TreeListNode node = treeList1.FocusedNode;
            if (node==null)
            {
                return;
            }
            object obj= node.GetValue(0);
            IFeatureLayer pFeaLyr=(IFeatureLayer)obj;
            m_CurrentLayer = pFeaLyr;
            bool isCheck= CheckTolerance();
            if (isCheck)
            {
                dgvFeatures.DataSource = null;
                
                List<IFeature> lstFea=FeatureClassWrapper.GetFeaturesFromFeatureClass(pFeaLyr.FeatureClass,null);
                List<IFeature> lstTinyFea=CheckTinyPloygon(m_dblTolerance, lstFea);
                initDataTable(pFeaLyr);
                LoadFeaturesToGrid(lstTinyFea, m_dt);
            }
        }

        

        private void treeList1_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            //获取当前的pFealyr
            m_CurrentLayer= e.Node.GetValue(0) as IFeatureLayer ;          
            initDataTable(m_CurrentLayer);
            List<IFeature> lstFea=FeatureClassWrapper.GetFeaturesFromFeatureClass(m_CurrentLayer.FeatureClass,null);
            LoadFeaturesToGrid(lstFea,m_dt);
        }

        private void dgvFeatures_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (m_CurrentLayer==null)
            {
                return;
            }
            int fidColumnIndex = -1;
            for (int i = 0; i < dgvFeatures.Columns.Count; i++)
            {
                if (dgvFeatures.Columns[i].Name == "FID")
                {
                    fidColumnIndex = i;
                    break;
                }
                if (dgvFeatures.Columns[i].Name.ToUpper() == "OBJECTID")
                {
                    fidColumnIndex = i;
                    break;
                }
            }
            if (fidColumnIndex == -1) return;
            IFeatureClass pfeatCls = m_CurrentLayer.FeatureClass;
            IFeature pFeat = pfeatCls.GetFeature(Convert.ToInt32(dgvFeatures.Rows[e.RowIndex].Cells[fidColumnIndex].Value));
            if (pFeat != null)
            {

                IEnvelope pEv = pFeat.Shape.Envelope;
                pEv.Expand(3,3, true);
                IActiveView pActiveView = m_Map as IActiveView;
               ((IActiveView)m_Map).Extent = pEv;
                //清空选择集
               m_Map.ClearSelection();
               m_Map.SelectFeature(m_CurrentLayer, pFeat);
             
                pActiveView.Refresh();
                //pActiveView.ScreenDisplay.UpdateWindow();
                //先定位后闪烁
               // MapWrapper.FlashDefaultGeometry(m_mapControl, pFeat.Shape);
                //选中指定的要素
                
            }
        }









    }
}
